const { execSync } = window.require("child_process");
const path = window.require("path");
const fs = window.require("fs");
const { dialog } = window.require("electron").remote;

export default function packPage(state, { treeData, that }) {
  let aimPath;
  let website_template = path.join(__dirname, "../../website_template");

  const loading = that.$loading({
    lock: true,
    text: "打包中...",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  //"D:\win-unpacked\resources\electron.asar\renderer"
  //"C:\Users\1234\Desktop\gogogo\JavaScript\easyWebsite\vue-jsx\dist_electron\win-unpacked\resources\electron.asar\renderer"
  //"C:\Users\1234\AppData\Local\Programs\vue-jsx\resources\electron.asar\renderer"
  //"C:\Users\1234\AppData\Local\Programs\vue-jsx\resources\electron.asar\renderer"

  //对图片路径进行替换
  for (const key in that.imgList) {
    if (Object.hasOwnProperty.call(that.imgList, key)) {
      treeData = treeData.replace(
        that.imgList[key].blob,
        `./img/${that.imgList[key].src.split("developPageImage/")[1]}`
      );
    }
  }

  setTimeout(() => {
    try {
      //写入网站代码
      fs.writeFileSync(
        path.join(website_template, "./src/App.vue"),
        `<script>
      export default {
        name: "App",
        data() {
          return {
            tree: ${treeData},
            pageName: "index", //页面名称
          };
        },
        methods: {},
        render(h) {
          return <div>{this.$explain(this, h, this.tree[this.pageName])}</div>;
        },
      };
      </script>
      `
      );

      //进行打包
      execSync(`cd ${website_template} && npm run build`);

      //选择存放目录
      aimPath = dialog.showOpenDialogSync({
        title: "请选择要存放的目录",
        properties: ["openFile", "openDirectory"],
      });
      if (aimPath == undefined) {
        that.$message({
          message: "请选择要存放的目录",
          type: "warning",
        });
      }

      if (aimPath == undefined) return loading.close();

      //复制源码
      /**
       * /y：不弹出“确认是否覆写已存在目标文件”的提示
       * /e：复制文件及子文件夹内所有内容，包括空文件夹（对比/s, /s不复制空文件夹）
       * /i：如果b不存在并且复制超过一个文件则默认b是目录名
       * /q：quiet，静默模式
       */
      execSync(
        `xcopy ${path.join(website_template, "./dist")} ${path.join(
          aimPath[0],
          "./dist"
        )} /y /e /i /q`
      );
      //复制图片
      execSync(
        `xcopy ${path.join(that.__filePath + "/developPageImage")} ${path.join(
          aimPath[0],
          "./dist/img"
        )} /y /e /i /q`
      );

      that.$message({
        message: "打包成功!",
        type: "success",
      });
    } catch (error) {
      console.error(error);
      that.$message.error({
        message: "打包失败!",
      });
    }
    loading.close();
  }, 500);
}
